package main

import (
	"flag"
	"github.com/gin-gonic/gin"
	"log"
	"my_gin_open/controller"
	"my_gin_open/middleware"
	"my_gin_open/model"
	rt "my_gin_open/runtime"
	"my_go_open/utils"
	"net/http"
)

func main() {
	ginMode := ""
	addrListen := ""
	flag.StringVar(&ginMode, "mode", "debug", "debug | test | release")
	flag.StringVar(&addrListen, "listen", "0.0.0.0:8765", "x.x.x.x:x")
	flag.Parse()
	gin.SetMode(ginMode)
	engine := gin.New()
	engine.Use(gin.CustomRecovery(func(c *gin.Context, err interface{}) {
		defer rt.SaveRTLog("recovery", c.Request.Method, c.Request.URL, c.Request.PostForm, c.Request.Header, c.RemoteIP(), err)
		c.AbortWithStatus(http.StatusInternalServerError)
	}), middleware.Cors, middleware.RateLimit)

	/* ---------- APIs ---------- */
	api := engine.Group("/api")
	{
		/* test */
		api.GET("/test/hi", controller.TestHi)
		api.GET("/test/recovery", controller.TestRecovery)
		/* captcha */
		captcha := api.Group("/captcha")
		{
			captcha.GET("/4.png", controller.Captcha)
			captcha.GET("/6.png", controller.Captcha6)
		}
		// controller.TableRoutes(api, model.TableTest)
		tableTest := api.Group("/table_test")
		{
			tableTest.GET("/get_one", controller.TableGetOne(model.TableTest, nil, nil))
			tableTest.POST("/add_one", controller.TableInsert(model.TableTest, 0, nil, nil))
			tableTest.POST("/update_one", controller.TableUpdate(model.TableTest, nil, nil))
			tableTest.GET("/list", controller.TableList(model.TableTest, func(c *gin.Context, row *utils.MysqlRow) (uint, error) {
				(*row)["queryWhere"] = "created_at > ? and id > ?"
				params := make([]interface{}, 0)
				params = append(params, "2022-09-12 00:00:00")
				params = append(params, "3")
				(*row)["params"] = params
				return 0, nil
			}, nil))
			tableTest.POST("/delete", controller.TableDelete(model.TableTest, nil, nil))
		}
	}

	log.Fatalln(engine.Run(addrListen))
}
